package common.impl;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;

import weibo4j.model.PostParameter;

public class HttpRequest {

	public static String post(String url, PostParameter[] params) {
		PostMethod postMethod = new PostMethod(url);
		if (null != params)
			for (int i = 0; i < params.length; i++) {
				if (!StringUtils.isEmpty(params[i].getValue()))
					postMethod.addParameter(params[i].getName(), params[i]
							.getValue());
			}
		HttpMethodParams param = postMethod.getParams();
		param.setContentCharset("UTF-8");
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		HttpClient httpClient = new HttpClient();
		String s = null;
		try {
			httpClient.executeMethod(postMethod);
			s = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			s = e.getMessage();
		} finally {
			postMethod.releaseConnection();
		}
		return s;
	}

	public static String get(String url, PostParameter[] params) {
		if (null != params) {
			for (int i = 0; i < params.length; i++) {
				if (StringUtils.isEmpty(params[i].getValue()))
					continue;
				if(i == 0)
					url += "?";
				else
					url += "&";
				url += params[i].getName() + "=" + params[i].getValue();
			}
		}
		HttpMethod getMethod = new GetMethod(url);
		HttpClient httpClient = new HttpClient();
		String s = null;
		try {
			httpClient.executeMethod(getMethod);
			s = getMethod.getResponseBodyAsString();
		} catch (Exception e) {
			s = e.getMessage();
		} finally {
			getMethod.releaseConnection();
		}
		return s;
	}
}
